<template>
  <div class="admin-user-edit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑用户' : '新建用户' }}</h2>
      <div class="header-actions">
        <button class="admin-btn" @click="goBack">返回列表</button>
        <button class="admin-btn admin-btn-primary" @click="saveUser">保存</button>
      </div>
    </div>
    
    <div class="loading-container" v-if="loading">
      <div class="loading-spinner"></div>
      <p>{{ isEdit ? '正在加载用户详情...' : '准备创建用户...' }}</p>
    </div>
    
    <div class="error-container" v-else-if="error">
      <div class="error-icon">❌</div>
      <h3>出错了</h3>
      <p>{{ error }}</p>
      <button class="admin-btn" @click="goBack">返回列表</button>
    </div>
    
    <div class="edit-form-container" v-else>
      <div class="admin-alert admin-alert-info" v-if="isEdit">
        <p>当前正在编辑ID为 <strong>{{ userId }}</strong> 的用户。</p>
      </div>
      
      <div class="admin-form edit-form">
        <div class="form-tabs">
          <div 
            class="form-tab" 
            :class="{ active: activeTab === 'basic' }"
            @click="activeTab = 'basic'"
          >
            基本信息
          </div>
          <div 
            class="form-tab" 
            :class="{ active: activeTab === 'security' }"
            @click="activeTab = 'security'"
          >
            安全设置
          </div>
          <div 
            class="form-tab" 
            :class="{ active: activeTab === 'permissions' }"
            @click="activeTab = 'permissions'"
          >
            权限管理
          </div>
        </div>
        
        <!-- 基本信息 -->
        <div class="form-tab-content" v-show="activeTab === 'basic'">
          <div class="user-avatar-section">
            <div class="avatar-preview">
              <img v-if="formData.avatar" :src="formData.avatar" alt="用户头像">
              <div v-else class="avatar-placeholder">
                {{ getUserInitials(formData.username) }}
              </div>
            </div>
            <div class="avatar-upload">
              <button class="admin-btn" @click="triggerAvatarUpload">上传头像</button>
              <button class="admin-btn" v-if="formData.avatar" @click="removeAvatar">移除头像</button>
              <input 
                type="file" 
                ref="avatarInput" 
                style="display: none" 
                @change="handleAvatarUpload"
                accept="image/*"
              >
              <div class="avatar-tip">建议上传正方形图片，JPG/PNG格式</div>
            </div>
          </div>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">用户名</label>
              <input
                type="text"
                v-model="formData.username"
                class="admin-form-input"
                placeholder="请输入用户名"
              >
              <div class="admin-form-error" v-if="errors.username">{{ errors.username }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label required">真实姓名</label>
              <input
                type="text"
                v-model="formData.realName"
                class="admin-form-input"
                placeholder="请输入真实姓名"
              >
              <div class="admin-form-error" v-if="errors.realName">{{ errors.realName }}</div>
            </div>
          </div>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">邮箱</label>
              <input
                type="email"
                v-model="formData.email"
                class="admin-form-input"
                placeholder="请输入邮箱"
              >
              <div class="admin-form-error" v-if="errors.email">{{ errors.email }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label">手机号</label>
              <input
                type="tel"
                v-model="formData.phone"
                class="admin-form-input"
                placeholder="请输入手机号"
              >
              <div class="admin-form-error" v-if="errors.phone">{{ errors.phone }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">个人简介</label>
              <textarea
                v-model="formData.bio"
                class="admin-form-input"
                placeholder="请输入个人简介"
                rows="4"
              ></textarea>
            </div>
          </div>
        </div>
        
        <!-- 安全设置 -->
        <div class="form-tab-content" v-show="activeTab === 'security'">
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">密码</label>
              <input
                type="password"
                v-model="formData.password"
                class="admin-form-input"
                placeholder="输入新密码，不修改请留空"
              >
              <div class="admin-form-error" v-if="errors.password">{{ errors.password }}</div>
              <div class="admin-form-helper">密码长度至少8位，包含字母和数字</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">确认密码</label>
              <input
                type="password"
                v-model="formData.confirmPassword"
                class="admin-form-input"
                placeholder="再次输入新密码"
              >
              <div class="admin-form-error" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">账号状态</label>
              <div class="status-options">
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="active">
                  <span class="status-label">活跃</span>
                  <span class="status-description">用户可以正常登录和使用系统</span>
                </label>
                
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="inactive">
                  <span class="status-label">非活跃</span>
                  <span class="status-description">用户可以登录但部分功能受限</span>
                </label>
                
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="blocked">
                  <span class="status-label">已封禁</span>
                  <span class="status-description">用户无法登录和使用系统</span>
                </label>
              </div>
              <div class="admin-form-error" v-if="errors.status">{{ errors.status }}</div>
            </div>
          </div>
          
          <div class="form-row" v-if="formData.status === 'blocked'">
            <div class="admin-form-item">
              <label class="admin-form-label">封禁原因</label>
              <textarea
                v-model="formData.blockReason"
                class="admin-form-input"
                placeholder="请输入封禁原因"
                rows="3"
              ></textarea>
            </div>
          </div>
        </div>
        
        <!-- 权限管理 -->
        <div class="form-tab-content" v-show="activeTab === 'permissions'">
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label required">用户角色</label>
              <div class="role-options">
                <label class="role-option">
                  <input type="radio" v-model="formData.role" value="user">
                  <div class="role-info">
                    <span class="role-name">普通用户</span>
                    <span class="role-description">基本权限，可参与挑战和任务</span>
                  </div>
                </label>
                
                <label class="role-option">
                  <input type="radio" v-model="formData.role" value="vip">
                  <div class="role-info">
                    <span class="role-name">VIP用户</span>
                    <span class="role-description">享受额外福利和特权</span>
                  </div>
                </label>
                
                <label class="role-option">
                  <input type="radio" v-model="formData.role" value="moderator">
                  <div class="role-info">
                    <span class="role-name">版主</span>
                    <span class="role-description">可管理评论和部分内容</span>
                  </div>
                </label>
              </div>
              <div class="admin-form-error" v-if="errors.role">{{ errors.role }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">积分设置</label>
              <div class="points-setting">
                <div class="current-points">
                  <span class="points-label">当前积分：</span>
                  <span class="points-value">{{ formData.points }}</span>
                </div>
                <div class="adjust-points">
                  <span class="adjust-label">调整积分：</span>
                  <input
                    type="number"
                    v-model="pointsAdjustment"
                    class="admin-form-input points-input"
                    placeholder="输入调整值"
                  >
                  <button 
                    class="admin-btn"
                    @click="adjustPoints"
                    :disabled="!pointsAdjustment"
                  >
                    应用
                  </button>
                </div>
              </div>
              <div class="admin-form-helper">正数增加积分，负数减少积分</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">特殊权限</label>
              <div class="permissions-list">
                <label class="permission-item">
                  <input type="checkbox" v-model="formData.permissions.createChallenges">
                  <span class="permission-name">创建挑战</span>
                </label>
                
                <label class="permission-item">
                  <input type="checkbox" v-model="formData.permissions.reviewContent">
                  <span class="permission-name">内容审核</span>
                </label>
                
                <label class="permission-item">
                  <input type="checkbox" v-model="formData.permissions.manageComments">
                  <span class="permission-name">管理评论</span>
                </label>
                
                <label class="permission-item">
                  <input type="checkbox" v-model="formData.permissions.exportData">
                  <span class="permission-name">导出数据</span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="form-actions">
        <button class="admin-btn" @click="goBack">取消</button>
        <button 
          class="admin-btn admin-btn-danger" 
          v-if="isEdit"
          @click="confirmDeleteUser"
        >
          删除用户
        </button>
        <button class="admin-btn admin-btn-primary" @click="saveUser">保存用户</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AdminUserEdit',
  data() {
    return {
      userId: this.$route.params.id,
      isEdit: !!this.$route.params.id,
      loading: false,
      error: null,
      activeTab: 'basic',
      pointsAdjustment: null,
      formData: {
        username: '',
        realName: '',
        email: '',
        phone: '',
        bio: '',
        avatar: null,
        password: '',
        confirmPassword: '',
        status: 'active',
        blockReason: '',
        role: 'user',
        points: 0,
        permissions: {
          createChallenges: false,
          reviewContent: false,
          manageComments: false,
          exportData: false
        }
      },
      errors: {}
    }
  },
  created() {
    if (this.isEdit) {
      this.fetchUserData()
    }
  },
  methods: {
    fetchUserData() {
      this.loading = true
      this.error = null
      
      // 模拟API调用获取用户数据
      setTimeout(() => {
        // 在实际应用中，这里会调用API获取用户数据
        if (this.userId === '1') {
          this.formData = {
            username: '张三',
            realName: '张大山',
            email: 'zhangsan@example.com',
            phone: '13800138000',
            bio: '环保爱好者，热衷于参与各种低碳环保活动。',
            avatar: null,
            password: '',
            confirmPassword: '',
            status: 'active',
            blockReason: '',
            role: 'user',
            points: 520,
            permissions: {
              createChallenges: false,
              reviewContent: false,
              manageComments: true,
              exportData: false
            }
          }
          this.loading = false
        } else {
          this.error = '未找到该用户数据'
          this.loading = false
        }
      }, 1000)
    },
    getUserInitials(username) {
      if (!username) return '?'
      return username.charAt(0).toUpperCase()
    },
    triggerAvatarUpload() {
      this.$refs.avatarInput.click()
    },
    handleAvatarUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件类型
      if (!file.type.match('image.*')) {
        this.errors.avatar = '请上传图片文件（JPG, PNG等）'
        return
      }
      
      // 检查文件大小
      if (file.size > 2 * 1024 * 1024) { // 2MB
        this.errors.avatar = '图片大小不能超过2MB'
        return
      }
      
      // 创建临时URL用于预览
      this.formData.avatar = URL.createObjectURL(file)
    },
    removeAvatar() {
      this.formData.avatar = null
      if (this.$refs.avatarInput) {
        this.$refs.avatarInput.value = null
      }
    },
    adjustPoints() {
      if (!this.pointsAdjustment) return
      
      const adjustment = parseInt(this.pointsAdjustment)
      if (isNaN(adjustment)) return
      
      this.formData.points += adjustment
      
      // 不允许积分为负
      if (this.formData.points < 0) {
        this.formData.points = 0
      }
      
      this.pointsAdjustment = null
    },
    validate() {
      this.errors = {}
      
      // 基本信息验证
      if (!this.formData.username) {
        this.errors.username = '请输入用户名'
      }
      
      if (!this.formData.realName) {
        this.errors.realName = '请输入真实姓名'
      }
      
      if (!this.formData.email) {
        this.errors.email = '请输入邮箱'
      } else if (!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(this.formData.email)) {
        this.errors.email = '邮箱格式不正确'
      }
      
      if (this.formData.phone && !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        this.errors.phone = '手机号格式不正确'
      }
      
      // 密码验证
      if (this.formData.password) {
        if (this.formData.password.length < 8) {
          this.errors.password = '密码长度至少8位'
        } else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(this.formData.password)) {
          this.errors.password = '密码必须包含字母和数字'
        }
        
        if (this.formData.password !== this.formData.confirmPassword) {
          this.errors.confirmPassword = '两次输入的密码不一致'
        }
      }
      
      // 角色验证
      if (!this.formData.role) {
        this.errors.role = '请选择用户角色'
      }
      
      return Object.keys(this.errors).length === 0
    },
    goBack() {
      this.$router.push('/admin/users')
    },
    saveUser() {
      if (!this.validate()) {
        // 切换到有错误的标签页
        if (this.errors.username || this.errors.realName || this.errors.email || this.errors.phone) {
          this.activeTab = 'basic'
        } else if (this.errors.password || this.errors.confirmPassword || this.errors.status) {
          this.activeTab = 'security'
        } else if (this.errors.role) {
          this.activeTab = 'permissions'
        }
        return
      }
      
      this.loading = true
      
      // 模拟API保存
      setTimeout(() => {
        alert(this.isEdit ? '用户更新成功！' : '用户创建成功！')
        this.loading = false
        this.goBack()
      }, 1000)
    },
    confirmDeleteUser() {
      if (confirm(`确定要删除用户"${this.formData.username}"吗？此操作不可恢复！`)) {
        this.loading = true
        
        // 模拟API删除
        setTimeout(() => {
          alert('用户已删除')
          this.loading = false
          this.goBack()
        }, 1000)
      }
    }
  }
}
</script>

<style scoped>
.admin-user-edit {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ff4d4f;
}

.edit-form-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.form-tab {
  padding: 12px 16px;
  cursor: pointer;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.65);
  position: relative;
  transition: all 0.3s;
}

.form-tab:hover {
  color: #1890ff;
}

.form-tab.active {
  color: #1890ff;
}

.form-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #1890ff;
}

.form-tab-content {
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.form-row {
  margin-bottom: 24px;
}

.form-row.two-col {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.admin-form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.admin-form-label.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.admin-form-helper {
  margin-top: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

/* 用户头像部分 */
.user-avatar-section {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  align-items: center;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  background-color: #1890ff;
  color: white;
  font-size: 40px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.avatar-tip {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

/* 状态选项 */
.status-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.status-option {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.status-option input {
  margin-top: 3px;
  margin-right: 8px;
}

.status-label {
  font-weight: 500;
  margin-right: 8px;
}

.status-description {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

/* 角色选项 */
.role-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.role-option {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
}

.role-option:hover {
  border-color: #40a9ff;
}

.role-option input {
  margin-top: 3px;
  margin-right: 8px;
}

.role-option input:checked + .role-info .role-name {
  color: #1890ff;
}

.role-info {
  display: flex;
  flex-direction: column;
}

.role-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.role-description {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

/* 积分设置 */
.points-setting {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.current-points {
  display: flex;
  align-items: center;
}

.points-value {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.adjust-points {
  display: flex;
  align-items: center;
  gap: 8px;
}

.adjust-label {
  margin-right: 8px;
}

.points-input {
  width: 150px;
}

/* 权限列表 */
.permissions-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.permission-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.permission-item input {
  margin-right: 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row.two-col {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .user-avatar-section {
    flex-direction: column;
    align-items: center;
  }
  
  .permissions-list {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-wrap: wrap;
  }
  
  .adjust-points {
    flex-wrap: wrap;
  }
}
</style> 